package com.selune.online.ordering.system.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created with IntelliJ IDEA.
 *
 * @author xiaoyp
 * @date 2020/4/1
 * <p>
 * Description:
 */
public class MultipartFileToFileUtils {
	
	/**
	 * MultipartFile 转 File
	 *
	 * @param file 文件
	 * @throws Exception 错误抛出
	 */
	public static File multipartFileToFile(MultipartFile file) throws Exception {
		
		File toFile = null;
		if (!ObjectUtils.isEmpty(file) && file.getSize() > 0) {
			InputStream ins;
			ins = file.getInputStream();
			toFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		return toFile;
	}
	
	/**
	 * 获取流文件
	 */
	private static void inputStreamToFile(InputStream ins, File file) {
		int len = 8192;
		
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除本地临时文件
	 *
	 * @param file 临时文件
	 */
	public static void deleteTempFile(File file) {
		if (file != null) {
			File del = new File(file.toURI());
			del.delete();
		}
	}
}